package com.dobby.okhttp.demo.yidian;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by jonas on 2017/2/24.
 */
public class YidianPublisher {

    private OkHttpClient okHttpClient = new OkHttpClient();

    private String cookie = null;

    private YidianPublisher(String cookie) {
        this.cookie = cookie;
    }

    public static YidianPublisher create(String cookie) throws Exception {
        if(cookie == null || cookie.length() == 0) {
            throw new Exception("cookie缺失");
        } else {
            return new YidianPublisher(cookie);
        }
    }

    private Map<String, String> addHeaders() throws Exception {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Accept","application/json, text/javascript, */*; q=0.01");
//        headers.put("Accept-Encoding","gzip, deflate");
        headers.put("Accept-Language","zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4");
        headers.put("Content-type","application/json; charset=utf-8");
        headers.put("Host","mp.yidianzixun.com");
        headers.put("Origin","http://mp.yidianzixun.com");
        headers.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
        headers.put("X-Requested-With","XMLHttpRequest");
        if(null != this.cookie) {
            headers.put("Cookie", this.cookie);
        } else {
            throw new Exception("缺少cookie信息");
        }
        return headers;
    }


    /**
     * 发布文章
     * @return
     */
    public String publishArticle(String title, String content) throws Exception {
        String draft = draft(title, content);
        JSONObject jsonObject = JSONObject.parseObject(draft);
        String postId = jsonObject.getString("id");
        String result = publish(postId);
        return result;
    }


    /**
     * 存草稿
     * @param title
     * @param content
     * @return
     */
    public String draft(String title, String content) throws Exception {
        String url = "http://mp.yidianzixun.com/model/Article";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", title);
        jsonObject.put("content", content);
        jsonObject.put("coverType", "default");
        jsonObject.put("cate", "民生");
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toJSONString());
        Request request = new Request.Builder()
                .url(url)
                .headers(Headers.of(addHeaders()))
                .post(requestBody)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if(response.isSuccessful()) {
            String jsonInfo = response.body().string();
            System.out.println(jsonInfo);
            return jsonInfo;
        } else {
            throw new Exception(response.body().string());
        }

    }


    /**
     * 发布文章
     * @param postId
     * @return
     */
    public String publish(String postId) throws Exception {
        String url = "http://mp.yidianzixun.com/api/post/publish?post_id=" + postId;
        Request request = new Request.Builder()
                .url(url)
                .headers(Headers.of(addHeaders()))
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if(response.isSuccessful()) {
            String jsonInfo = response.body().string();
            System.out.println(jsonInfo);
            return jsonInfo;
        } else {
            throw new Exception(response.body().string());
        }
    }


    public String getArticleInfo(String postId) throws Exception {
        String url = "http://mp.yidianzixun.com/model/Article/" + postId;  //17363048  17355121
        Request request = new Request.Builder()
                .url(url)
                .headers(Headers.of(addHeaders()))
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if(response.isSuccessful()) {
            String jsonInfo = response.body().string();
            JSONObject resultJson = JSONObject.parseObject(jsonInfo);
            String comment = resultJson.getString("comment");
            Integer status = resultJson.getInteger("status");
            String newsId = resultJson.getString("news_id");

            JSONObject returnInfo = new JSONObject();
            if(status.equals(AuditStatus.UNAUDITED_A.getCode()) || status.equals(AuditStatus.UNAUDITED_B.getCode())
                    || status.equals(AuditStatus.UNAUDITED_C.getCode()) || status.equals(AuditStatus.UNAUDITED_D.getCode())) {
                // 待审核
                returnInfo.put("auditStatus","待审核");
            } else if(status.equals(AuditStatus.DELETED.getCode())) {
                // 已删除
                returnInfo.put("auditStatus","已删除");
            } else if(status.equals(AuditStatus.PUBLISHED_A.getCode()) || status.equals(AuditStatus.PUBLISHED_B.getCode())) {
                // 已发布
                returnInfo.put("auditStatus","已发布");
                returnInfo.put("newsId", newsId);
                returnInfo.put("accessUrl", "http://www.yidianzixun.com/home?page=article&id=" + newsId);
            } else if(status.equals(AuditStatus.UNPASSED.getCode())) {
                // 未通过
                returnInfo.put("auditStatus","未通过");
                returnInfo.put("comment", comment);
            } else if(status.equals(AuditStatus.DRAFT.getCode())) {
                // 草稿
                returnInfo.put("auditStatus","草稿");
            }
            return returnInfo.toJSONString();
        } else {
            throw new Exception(response.body().string());
        }
    }


    public Map<String, Integer>  getStatInfo(String newsId) throws Exception {
        Map<String, Integer> map = new HashMap<String, Integer>();
        String url = "http://mp.yidianzixun.com/model/Article?page=1&status=2,7&has_data=1&type=original&title=&page_size=" + Integer.MAX_VALUE;
        Request request = new Request.Builder()
                .url(url)
                .headers(Headers.of(addHeaders()))
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if(response.isSuccessful()) {
            String jsonInfo = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(jsonInfo);
            JSONArray posts = (JSONArray) jsonObject.get("posts");
            for (Object obj : posts) {
                JSONObject jobj = (JSONObject) obj;
                if(newsId.equals(jobj.getString("news_id"))) {
                    //
                }
            }

        }
        return map;
    }

}
